import axios from 'axios'
import qs from 'qs'
import {apiBasePath} from './config.js'

const baseUrl = import.meta.env.BASE_URL
axios.defaults.timeout = 3 * 1000
axios.defaults.baseURL = apiBasePath


axios.interceptors.response.use(
    response => {
        const data = response.data
        const code = data.code
        if (code === 403) {
            let url = baseUrl.replace(/\/$/, '')
            window.location.href = `${url}/#/login`
        }
        return response
    },
    error => {
        return Promise.reject({
            code: 500,
            message: '服务器出错'
        })
    }
)

axios.interceptors.request.use(
    config => {
        return config
    },
    error => {
        return Promise.reject(error)
    }
)


function get(url, params) {
    return new Promise((resolve) => {
        axios
            .get(url, {
                params: params,
                paramsSerializer: params => {
                    return qs.stringify(params, {
                        indices: false,
                        arrayFormat: 'repeat'
                    })
                },
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8'
                }
            })
            .then(res => {
                if (res) {
                    const data = res.data
                    resolve({
                        code: data.code,
                        data: data.data || '',
                        err: data.code === 200 ? void 0 : data.message
                    })
                }
            })
            .catch(e => {
                console.error(e)
                resolve({
                    code: 500,
                    data: '',
                    err: e.message
                })
            })
    })
}

export default {
    get
}
